<template>
  <section class="component expression-base">
    <p v-if="preView" v-html="preViewExpressionStr"></p>
    <data-box class="expression-base-data-box" :data="expressionDataSet" :key="JSON.stringify(new Date())">
      <template slot="columns">
        <el-table-column label="链接关系" prop="relation">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.relation" @change="sendData" clearable>
              <el-option v-for="{name,value} of getRelationOptions(scope.$index)" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="左括号" prop="leftBracket">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.leftBracket" placeholder="可空置" @change="sendData" clearable>
              <el-option v-for="{name,value} of bracket.left" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段" prop="variable" :min-width="$helper.getColumnWidth(4)">
          <template slot-scope="scope">
            <el-tooltip :content="changeTwo(scope.row)" placement="top" :disabled="scope.row.variable && scope.row.name.variable === 0">
              <el-select :disabled='openData===3||disabledData' v-model="scope.row.variable" placeholder="请选择字段" @change="onVariableChange(scope.row)">
                <el-option v-for="{name,field} of fieldDataSet" :key="field" :label="name" :value="field"></el-option>
              </el-select>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作符" prop="symbol" :min-width="$helper.getColumnWidth(4)">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.symbol" placeholder="请选择操作符" @change="sendData" clearable>
              <el-option v-for="{name,value} of getSymbolOptions(scope.row.variable)" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="期望值" prop="value" :min-width="$helper.getColumnWidth(5)">
          <template slot-scope="scope">
            <el-tooltip effect="dark" :content="changeOne(scope.row)" placement="top" v-if="scope.row.operateType === 'SELECT'||scope.row.operateType === undefined" :disabled="scope.row.value && scope.row.value.length === 0">
              <el-select :disabled='openData===3||disabledData' v-model="scope.row.value" @change="sendData();getName(scope.row.value, scope.$index)" clearable>
                <el-option v-for="{name,code} of getValueOptions(scope.row.variable)" :key="code" :label="name" :value="code"></el-option>
              </el-select>
            </el-tooltip>
            <el-tooltip effect="dark" :content="scope.row.value" placement="top" v-if="scope.row.operateType !=='SELECT' && scope.row.operateType !== 'CASCADER'" :disabled="scope.row.value && scope.row.value.length === 0">
              <el-input v-model.trim="scope.row.value" placeholder="请输入期望值" @change="sendData" clearable :disabled='openData===3||disabledData'></el-input>
            </el-tooltip>
            <el-cascader v-model="scope.row.value" v-if="scope.row.operateType === 'CASCADER'" :options="getValueOptions(scope.row.variable)" change-on-select :show-all-levels="false" clearable :disabled='openData===3||disabledData'></el-cascader>
          </template>
        </el-table-column>
        <el-table-column label="右括号" prop="rightBracket">
          <template slot-scope="scope">
            <el-select v-model="scope.row.rightBracket" placeholder="可空置" @change="sendData" clearable :disabled='openData===3||disabledData'>
              <el-option v-for="{name,value} of bracket.right" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" v-if="!disabledData">
          <template slot-scope="scope">
            <el-button type="text" :disabled='openData===3' @click="deleteClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </data-box>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Model, Watch } from "vue-property-decorator";
import { Form } from "element-ui";
import { operates, links, IstrategyInfo } from "./strategy-helper.config";
import DataBox from "~/components/common/data-box.vue";
import { StrategyConfigService } from "~/services/dataimp-service/strategy-config.service";
import { EntityIdService } from "~/services/management-service/entity-id.service";
import { RuleRemovedService } from "~/services/domain-service/rule-removed.service"
import { DictService } from "~/utils/dict.service";
import { CityService } from "~/utils/city.service"
import SvgIcon from "~/components/common/svg-icon.vue"

@Component({
  components: {

    SvgIcon
  }
})
export default class ExpressionBase extends Vue {
  @Dependencies(StrategyConfigService) private strategyConfigService: StrategyConfigService;
  @Dependencies(EntityIdService) private entityIdService: EntityIdService;
  @Dependencies(RuleRemovedService) private ruleRemovedService: RuleRemovedService;

  @Model("expressin-change")
  private expressionDataSet: IstrategyInfo[];

  @Prop({
    type: Number
  })
  private openData: number
  @Prop({ type: String }) private modifyData
  @Prop({ type: Boolean }) private disabledData: boolean
  @Prop({
    type: Boolean
  })
  private flag: boolean
  @Prop({ type: String }) private val: string
  @Prop({ type: Boolean }) private show: boolean
  @Prop({ type: String }) private entityIdStr: string

  private bracket = links.bracket;
  private fieldDataSet: any[] = []
  private preView = false;
  @Emit("expressin-change")
  private emitExpressionDataSet (data) { }

  @Watch('flag') private refeshData () { this.getFieldDataSet() }


  private mounted () { this.getFieldDataSet() }
  /**
   * 加载支持的字段和关联数据
   */
  private getFieldDataSet () {
    if (this.flag) { if (this.entityIdStr === 'ENTITYID' || this.entityIdStr === 'ID_STRATEGY') { this.entityId() } } else { this.rule(); }
  }

  /**
   * 获取实体ID支持字段及关联数据
   */
  private entityId () { this.entityIdService.getEntityFields().subscribe(data => this.fieldDataSet = data) }
  /**
   * 获取规则剔除支持字段及关联数据
   */
  private rule () { this.ruleRemovedService.getRuleEliminateFields().subscribe(data => this.fieldDataSet = data) }

  private getName (val, index) {
    this.getValueOptions(this.expressionDataSet[index].variable).forEach(e => {
      if (e.code === val) {
        this.$nextTick(() => {
          this.$set(this.expressionDataSet[index], 'name', e.name)
        })
      }
    })
  }

  private deleteClick (index) {
    this.expressionDataSet.splice(index, 1)
    if (index === 0) {
      // this.expressionDataSet[index].relation = " "
    }
    this.sendData()
  }
  /**
   * 期望值tooltip
   */
  private changeOne (row) {
    if (!!this.getValueOptions(row.variable)) {
      const obj = this.getValueOptions(row.variable).find(f => row.value === f.code)
      return obj && obj.name
    }
  }
  /**
   * 字段tooltip
   */
  private changeTwo (row) {
    const obj = this.fieldDataSet.find(v => row.variable === v.field)
    return obj && obj.name
  }
  private sendData () {
    this.emitExpressionDataSet(this.expressionDataSet.map(v => ({ ...v })))
  }

  /**
   * 新增行的时候判断 连接符是什么
   */
  private getRelationOptions (index: number) {
    return index === 0 ? links.relation.first : links.relation.normal
  }

  private get preViewExpressionStr () {
    let str = ""
    str = this.expressionDataSet.map((v: IstrategyInfo) => {
      return [v.relation, v.leftBracket, v.variable, v.symbol, v.value, v.rightBracket].join(' ')
    }).join(' ')
    return str
  }

  /**
   * 字段值变化，其他的数据需要清空重新设置
   */
  private onVariableChange (row: IstrategyInfo, index) {
    console.log('row',row)

    row.symbol = ""
    row.value = ''
    row.name = ''
    if (row.cascaderValue) row.cascaderValue = []
    row.operateType = this.valueOperateType(row.variable)
    this.sendData()
  }

  // private onCascaderChange (row: IstrategyInfo, values: string[]) {
  //   row.value = values.length ? values[values.length - 1] : ''
  //   this.sendData()
  // }


  /**
   * 根据字段获取需要的操作符
   */
  private getSymbolOptions (field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    return fieldConfig ? operates.filter(x => x.enable.includes(fieldConfig.symbol)) : []
  }

  /**
   * 获取操作类型
   */
  private valueOperateType (field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    if (!fieldConfig) return ''
    let type = "INPUT"
    switch (fieldConfig.source) {
      case "DICT":
      case "DATA":
        type = "SELECT"
        break;
      case "OTHER":
        type = this.getOtherType(fieldConfig.key)
        break;
      default:
        break;
    }
    return type
  }

  /**
   * 其他数据的数据类型
   */
  private getOtherType (key) {
    let type = "INPUT"
    switch (key) {
      case 'CITY':
        type = "CASCADER"
        break;
      case 'DATE':
        type = "DATEPTCKER"
        break;
      default:
        break;
    }
    return type
  }

  /**
   * 获取值选择数据源
   */
  private getValueOptions (field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    const source: any = []
    if (!fieldConfig) return []
    if (fieldConfig.source === "DICT") {
      // 如果是数据字典，则获取数据字典数据作为期望值的数据源
      return DictService.getDictData(fieldConfig.key)
    } else if (fieldConfig.source === "DATA") {
      return fieldConfig.dataList
    } else {
      return this.getLocalData(fieldConfig.key)
    }
  }

  /**
   * 获取值选择数据源-- 本地数据源
   */
  private getLocalData (type: string) {
    let data: any = []
    switch (type) {
      case "CITY":
        data = CityService.getCityData({ level: 2 })
        break;
      default:
        break;
    }
    return data
  }

}
</script>

<style lang="less" scoped>
.component.expression-base {
  .expression-base-data-box {
    padding: 0;
  }
}
</style>
